package com.icss.ah.base.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.icss.ah.base.action.BaseAction;

@Controller
@Scope("prototype")
public class DownloadAction extends BaseAction{

	private String alaramPic;
	
	public void downloadPic() throws ServletException, IOException{
		HttpServletRequest request = this.getRequest();
		HttpServletResponse response = this.getResponse();
		String path = request.getRequestURI();
		if(path.toLowerCase().endsWith("jpg")){
			response.setContentType("image/jpg");
		}else if(path.toLowerCase().endsWith("bmp")){
			response.setContentType("image/bmp");
		}else if(path.toLowerCase().endsWith("gif")){
			response.setContentType("image/gif");
		}else if(path.toLowerCase().endsWith("jpeg")){
			response.setContentType("image/jpeg");
		}else if(path.toLowerCase().endsWith("png")){
			response.setContentType("image/png");
		}else{
			response.setContentType("application/octet-stream");
		}
		String pic = request.getParameter("alaramPic"); 
		pic = pic == null ? "" : pic;
		if(pic.equals("")){
			response.sendRedirect("error/nopicture.jpg");
		} else {
			String file_upload_url = "/uploadImage/";
			String imagePath = file_upload_url.replaceAll("\\\\", "/")+pic;
			InputStream in = null;
			OutputStream out = null;
			String filePath = imagePath;
			try{
				if (!new File(filePath).exists()) {
					response.sendRedirect("error/nopicture.jpg");
				} else {
					in = new FileInputStream(filePath);
					out = response.getOutputStream();
					byte[] b = new byte[512];
					int len = 0;
					while ((len = in.read(b)) != -1) {
						out.write(b, 0, len);
					}
				}
			}catch (IOException e) {
//				e.printStackTrace();
				System.out.println("请求文件未找到："+path);
			}
			finally{
				if(in!=null){
					in.close();
				}
				if(out!=null){
					out.flush();
					out.close();
				}
			}
		}
	}
	

	public String getAlaramPic() {
		return alaramPic;
	}

	public void setAlaramPic(String alaramPic) {
		this.alaramPic = alaramPic;
	}
}
